package com.example.taobaou.ui.Custom;

import android.content.Context;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

/**
 * 实现自动轮播功能
 */
public class AutoLoopViewPager extends ViewPager {

    public static final long DEFAULT_DURATION = 3000;
    private long mDuration = DEFAULT_DURATION;
    public AutoLoopViewPager(@NonNull Context context) {
        super(context);
    }

    public AutoLoopViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    private boolean isLoop = false;

    public void startLoop() {
        isLoop = true;
        post(mTask);
    }

    private Runnable mTask = new Runnable() {
        @Override
        public void run() {
            int currentItem = getCurrentItem();
            currentItem++;
            setCurrentItem(currentItem);
            if (isLoop) {
                postDelayed(this, 3000);
            }
        }
    } ;

    public void stopLoop() {
        removeCallbacks(mTask);
        isLoop = false;
    }

    /**
     * 设置轮播图切换时长
     * @param mDuration 单位： 毫秒
     */
    public void setmDuration(long mDuration) {
        this.mDuration = mDuration;
    }
}
